import os
import json
import math
import uuid
import datetime
import requests
from docx import Document

from django.views import View
from django.core.paginator import Paginator
from django.http import JsonResponse, HttpResponse

from KG_manage import settings
from kg_code_manage import models
from kg_code_manage.models import History
from django.shortcuts import render, redirect

from kg_code_manage.utils import excel_to_dict, insert_csv

project_base_path = os.getcwd()


def index(request):
    return render(request, 'index.html')


def base_model(request):
    """ 基础模型 """
    base_model_obj = models.Base_model.objects.filter()
    return render(request, 'knowledge_building/model_create_new.html', {"base_model_obj": base_model_obj})


class Add_base_model(View):
    """ 基础模型 - 添加 """

    def get(self, request):
        return render(request, 'knowledge_building/add_base_model.html')

    def post(self, request):
        model_name = request.POST.get("model_name", "")
        model_type = request.POST.get("model_type", "")
        try:
            models.Base_model.objects.create(name=model_name, type=model_type)
            res_data = {"code": 1, "msg": "基础模型创建成功"}
        except Exception:
            res_data = {"code": 0, "msg": "基础模型创建失败，请重试！！！"}
        return JsonResponse(res_data)


class Edit_base_model(View):
    """ 基础模型 - 编辑 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Base_model.objects.filter(pk=model_id).first()
        return render(request, 'knowledge_building/edit_base_model.html', {"model_obj": model_obj})

    def post(self, request):
        model_id = request.POST.get("model_id", "")
        model_name = request.POST.get("model_name", "")
        model_type = request.POST.get("model_type", "")
        try:
            models.Base_model.objects.filter(pk=model_id).update(name=model_name, type=model_type)
            res_data = {"code": 1, "msg": "基础模型修改成功"}
        except Exception:
            res_data = {"code": 0, "msg": "基础模型修改失败，请重试！！！"}
        return JsonResponse(res_data)


def delete_base_model(request, id):
    """ 基础模型 - 删除 """
    models.Base_model.objects.filter(pk=id).delete()
    return redirect('base_model')


def model(request):
    if request.method == "GET":
        sign = request.GET.get("sign")
        return render(request, "knowledge_building/model_create.html", {"sign": sign})
    else:
        # 上传文件
        file_type = request.POST.get('file_type')
        file_obj = request.FILES.get('file')
        file_path = os.path.join(project_base_path, 'upload_file', file_obj.name)
        try:
            with open(file_path, 'wb') as f:
                for chunk in file_obj.chunks():
                    f.write(chunk, )
        except Exception as e:
            pass

        """ 返回数据格式示例
        res_data = [{
            "id": "10002",
            "head_node": "异构知识的统一存储、映射、检索和接口技术",
            "head_type": "项目",
            "relationship": "技术指标",
            "tail_node": "异构知识种类不少于5种；知识的存储容量规模达到万级，不少于1GB；",
            "tail_type": "技术指标"
        }]
        """

        if file_type == "csv":
            res_data = excel_to_dict(file_path).get("data")
        elif file_type == "txt":
            res_data = []
            with open(file_path, 'r', encoding='utf-8') as fout:
                txt_content_list = fout.readlines()
                for i in range(len(txt_content_list)):
                    res_dic = {}
                    if i == 0:
                        continue
                    elif ":" in txt_content_list[i]:
                        tail_node_type = txt_content_list[i].split(":")
                        res_dic['head_node'] = txt_content_list[0].strip('\n')
                        res_dic['head_type'] = "项目"
                        res_dic['relationship'] = tail_node_type[0].strip('\n')
                        res_dic['tail_node'] = tail_node_type[1].strip('\n')
                        res_dic['tail_type'] = tail_node_type[0].strip('\n')
                        res_data.append(res_dic)
        elif file_type == "docx,doc":
            res_data = []
            res_dic = {
                "id": None,
                "head_node": None,
                "head_type": "项目",
                "relationship": None,
                "tail_node": None,
                "tail_type": None
            }

            doc = Document(file_path)
            split_num = None
            split_key_word = None
            for i in range(len(doc.paragraphs)):
                if i == 0:
                    res_dic['head_node'] = doc.paragraphs[i].text
                    continue
                if ":" in doc.paragraphs[i].text:
                    if doc.paragraphs[i].text.split(':')[-1]:
                        if split_num:
                            res_dic['head_node'] = doc.paragraphs[0].text
                            res_dic['relationship'] = split_key_word
                            res_dic['tail_node'] = doc.paragraphs[i].text.split(':')[-1]
                            res_dic['tail_type'] = doc.paragraphs[i].text.split(':')[0]
                        else:
                            res_dic['head_node'] = doc.paragraphs[0].text
                            res_dic['relationship'] = doc.paragraphs[i].text.split(':')[0]
                            res_dic['tail_node'] = doc.paragraphs[i].text.split(':')[-1]
                            res_dic['tail_type'] = doc.paragraphs[i].text.split(':')[0]
                        res_data.append(res_dic)
                        res_dic = {
                            "id": None,
                            "head_node": None,
                            "head_type": "项目",
                            "relationship": None,
                            "tail_node": None,
                            "tail_type": None
                        }
                    else:
                        split_num = i
                        split_key_word = doc.paragraphs[i].text.split(':')[0]

        elif file_type == "html":
            file_name = file_obj.name.split(".")[-2]
            file_path = os.path.join(project_base_path, 'test_folder', 'html_result', file_name)
            with open(file_path, 'r', encoding='utf-8') as fout:
                origin_data = json.loads(fout.read())
            res_data = origin_data.get("data")
        elif file_type == "sql":
            file_name = file_obj.name.split(".")[-2]
            file_path = os.path.join(project_base_path, 'test_folder', 'sql_result', file_name)
            with open(file_path, 'r', encoding='utf-8') as fout:
                origin_data = json.loads(fout.read())
            res_data = origin_data.get("data")

        res = {'code': 0, 'data': res_data}
        return JsonResponse(res)


def insert_map(request):
    """ 插入图谱 """
    insert_map_data = json.loads(request.POST.get("insert_map_data"))
    for sg_map in insert_map_data:
        # 插入实体节点
        head_node = sg_map.get("head_node")
        head_type = sg_map.get("head_type")
        uuid_head_node = str(uuid.uuid5(uuid.NAMESPACE_DNS, head_node))
        create_time1 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        res_data1 = {"label": head_type, "uuid": uuid_head_node, "name": head_node, "created_time": create_time1}
        response1 = requests.post(settings.neo4j_ip + '/kg/node/insert', data=res_data1)

        tail_node = sg_map.get("tail_node")
        tail_type = sg_map.get("tail_type")
        uuid_tail_node = str(uuid.uuid5(uuid.NAMESPACE_DNS, tail_node))
        create_time2 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        res_data2 = {"label": tail_type, "uuid": uuid_tail_node, "name": tail_node, "created_time": create_time2}
        response2 = requests.post(settings.neo4j_ip + '/kg/node/insert', data=res_data2)

        # 插入实体之间的关系
        relation = sg_map.get("relation")
        create_time3 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        res_data3 = {"start_node_uuid": uuid_head_node, "end_node_uuid": uuid_tail_node, "relation_type": relation, "created_time": create_time3}
        response3 = requests.post(settings.neo4j_ip + '/kg/edge/insert', data=res_data3)

    res = {'code': 0, 'data': "已插入到知识图谱"}
    return JsonResponse(res)


def knowledge(request):
    if request.method == "GET":
        return render(request, 'useless/knowledge_creat.html')


def map_preview(request):
    """ 抽取的信息知识图谱预览 """
    insert_map_data = json.loads(request.GET.get("insert_map_data"))
    datas = []
    edgeall = []
    for sg_map in insert_map_data:
        head_node = sg_map.get("head_node")
        head_type = sg_map.get("head_type")
        uuid_head_node = str(uuid.uuid5(uuid.NAMESPACE_DNS, head_node))
        create_time1 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        datas.append({"id": uuid_head_node, "label": head_type, "uuid": uuid_head_node, "properties": {"name": head_node, "create_time": create_time1}})

        tail_node = sg_map.get("tail_node")
        tail_type = sg_map.get("tail_type")
        uuid_tail_node = str(uuid.uuid5(uuid.NAMESPACE_DNS, tail_node))
        create_time2 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        datas.append({"id": uuid_tail_node, "label": tail_type, "uuid": uuid_tail_node, "properties": {"name": tail_node, "create_time": create_time2}})

        relation = sg_map.get("relation")
        edgeall.append({"source": uuid_head_node, "target": uuid_tail_node, "type": relation})

    return render(request, 'knowledge_building/map_previews.html', {"datas": datas, "edgeall": edgeall})


def knowledge_wikipedia(request):
    """ 知识百科 """
    return render(request, 'useless/knowledge_wikipedia.html')


def wikipedia_classification(request):
    """ 百科分类展示 """
    wikipedia_template_obj = models.Wikipedia_template.objects.filter()
    return render(request, 'wikipedia_template/wikipedia_classification.html', {'wikipedia_template_obj': wikipedia_template_obj})


def search_wikipedia_classification(request):
    """ 百科分类搜索 """
    wikipedia_classification = request.GET.get("wikipedia_classification")
    wikipedia_template_obj = models.Wikipedia_template.objects.filter(name__icontains=wikipedia_classification)
    return render(request, 'wikipedia_template/wikipedia_classification.html', {'wikipedia_template_obj': wikipedia_template_obj})


def wikipedia_entry(request):
    """ 百科词条 - 展示 """
    knowledge_card_obj = models.Wikipedia_entry.objects.filter()
    return render(request, 'wikipedia_entry/wikipedia_entry.html', {"knowledge_card_obj": knowledge_card_obj})


def search_wikipedia_entry(request):
    """ 百科词条 - 搜索 """
    wikipedia_entry_name = request.GET.get("wikipedia_entry_name")
    knowledge_card_obj = models.Wikipedia_entry.objects.filter(name__icontains=wikipedia_entry_name)
    return render(request, 'wikipedia_entry/wikipedia_entry.html', {"knowledge_card_obj": knowledge_card_obj})


def delete_wikipedia_entry(request, id):
    models.Wikipedia_entry.objects.filter(pk=id).delete()
    return redirect('wikipedia_entry')


class Add_wikipedia_entry(View):
    """ 百科词条 - 添加 """

    def get(self, request):
        return render(request, 'wikipedia_entry/add_wikipedia_entry.html')

    def post(self, request):
        name = request.POST.get("name")
        content = request.POST.get("content")
        models.Wikipedia_entry.objects.create(name=name, content=content)
        return redirect('wikipedia_entry')


class Edit_wikipedia_entry(View):
    """ 百科词条 - 编辑 """

    def get(self, request, id):
        wikipedia_entry_obj = models.Wikipedia_entry.objects.filter(pk=id).first()
        return render(request, 'wikipedia_entry/edit_wikipedia_entry.html', {"wikipedia_entry_obj": wikipedia_entry_obj})

    def post(self, request, id):
        name = request.POST.get("name")
        content = request.POST.get("content")
        models.Wikipedia_entry.objects.filter(pk=id).update(name=name, content=content)
        return redirect('wikipedia_entry')


class Wikipedia_template(View):
    def get(self, request):
        all_data = []
        for single_data in models.Wikipedia_template.objects.filter():
            single_data_dict = {}
            id = single_data.id
            name = single_data.name
            content = single_data.content
            card_template = single_data.card_template
            if card_template:
                card_id_list = [int(card_id) for card_id in card_template.split('，')]
                card_name_list = []
                for sg_card_id in card_id_list:
                    if models.Card_template.objects.filter(pk=sg_card_id).exists():
                        sg_card_name = models.Card_template.objects.filter(pk=sg_card_id).first().name
                        card_name_list.append(sg_card_name)
                mu_card_name = '，'.join(card_name_list)
            else:
                mu_card_name = ''

            single_data_dict["id"] = id
            single_data_dict["name"] = name
            single_data_dict["content"] = content
            single_data_dict["mu_card_name"] = mu_card_name
            all_data.append(single_data_dict)

        return render(request, 'wikipedia_template/wikipedia_template.html', {'all_data': all_data})

    def post(self, request):
        """ 批量删除 """
        id_list = request.POST.getlist('checked')
        data_obj = models.Wikipedia_template.objects.filter(id__in=id_list)
        data_obj.delete()
        return redirect(request.path)


def search_wikipedia(request):
    """ 百科模板 - 搜索 """
    template_name = request.GET.get("template_name")
    all_data = models.Wikipedia_template.objects.filter(name__icontains=template_name)
    return render(request, 'wikipedia_template/wikipedia_template.html', {'all_data': all_data})


class Add_wikipedia(View):
    """ 百科模板 - 添加 """

    def get(self, request):
        card_list = models.Card_template.objects.filter()
        return render(request, 'wikipedia_template/add_wikipedia_template.html', {"card_list": card_list})

    def post(self, request):
        name = request.POST.get("name")
        content = request.POST.get("content")
        card_template = '，'.join(request.POST.getlist("card_template"))
        models.Wikipedia_template.objects.create(name=name, content=content, card_template=card_template)
        return redirect('wikipedia_template')


class Edit_wikipedia(View):
    """ 百科模板 - 编辑 """

    def get(self, request, id):
        Wikipedia_template = models.Wikipedia_template.objects.filter(pk=id).first()
        card_id_list = [] if Wikipedia_template.card_template == '' else Wikipedia_template.card_template.split('，')

        selected_card_list = models.Card_template.objects.filter(id__in=card_id_list)
        selected_card_id = [sg_card.id for sg_card in selected_card_list]

        all_card_list = models.Card_template.objects.filter()
        return render(request, 'wikipedia_template/edit_wikipedia_template.html', {"Wikipedia_template": Wikipedia_template, "all_card_list": all_card_list, "selected_card_id": selected_card_id})

    def post(self, request, id):
        name = request.POST.get("name")
        content = request.POST.get("content")
        card_template = '，'.join(request.POST.getlist("card_template"))
        models.Wikipedia_template.objects.filter(pk=id).update(name=name, content=content, card_template=card_template)
        return redirect('wikipedia_template')


def delete_wikipedia(request, n):
    """ 百科模板 - 删除 """
    models.Wikipedia_template.objects.filter(id=n).delete()
    return redirect('wikipedia_template')


def preview_wikipedia(request, n):
    """ 百科模板 - 预览 """
    template_obj = models.Wikipedia_template.objects.filter(pk=n).first()
    template_name = template_obj.name
    template_content = template_obj.content
    all_content_list = template_content.split("，")[1:]

    # 知识卡片模板内容
    card_template_list = [] if template_obj.card_template == '' else template_obj.card_template.split('，')
    card_template = models.Card_template.objects.filter(id__in=card_template_list)
    all_card_list = []

    for sg_ct in card_template:
        card_list = sg_ct.content.split("，")
        card_dict = {"left": card_list[:math.ceil(len(card_list) / 2)], "right": card_list[math.ceil(len(card_list) / 2):]}
        all_card_list.append(card_dict)

    return render(request, 'wikipedia_template/template_preview.html', {"template_name": template_name, "data_list": all_content_list, "all_card_list": all_card_list})


class Require_wikipedia(View):
    """ 需求百科 - 展示 """

    def get(self, request):
        # 查询所有的模板名称
        template_name_list = [{"id": sg_tem.id, "name": sg_tem.name} for sg_tem in models.Wikipedia_template.objects.filter()]
        # 查询所有的知识卡片名称
        card_name_list = [{"id": sg_card.id, "name": sg_card.name} for sg_card in models.Knowledge_card.objects.filter()]

        # 查询所有的需求百科
        all_wikipedia_data = models.Require_wikipedia.objects.filter()
        res_data = [{"id": sg_data.id, "name": sg_data.name, "create_time": sg_data.create_time} for sg_data in all_wikipedia_data]
        return render(request, 'require_wikipedia/require_wikipedia.html', {"template_name_list": template_name_list, "card_name_list": card_name_list, "res_data": res_data})

    def post(self, request):
        choiced_template_id = request.POST.get("template_choiced")
        choiced_card_id = request.POST.get("knowledge_card_choiced")
        template_content = models.Wikipedia_template.objects.filter(id=choiced_template_id).first().content
        card_content = models.Knowledge_card.objects.filter(id=choiced_card_id).first().content
        template_content_list = template_content.split('，')
        return render(request, 'require_wikipedia/add_require_wikipedia.html',
                      {'template_content_list': template_content_list, 'template_content': template_content, 'card_content': card_content, 'choiced_card_id': choiced_card_id})


def add_require_wikipedia(request):
    """ 需求百科 - 添加 """
    id = request.POST.get("id")
    name = request.POST.get("name")
    all_tem = request.POST.get("all_tem")
    card_id = request.POST.get("card_id")
    template_content_list = all_tem.split('，')
    template_content_dict = {}
    for sg_tem_con in template_content_list:
        template_content_dict[sg_tem_con] = request.POST.get(sg_tem_con)
    template_content_str = json.dumps(template_content_dict)

    if id:
        models.Require_wikipedia.objects.filter(id=id).update(name=name, content=template_content_str, knowledge_card=card_id)
    else:
        models.Require_wikipedia.objects.create(name=name, content=template_content_str, knowledge_card=card_id)
    return redirect('require_wikipedia')


def preview_require_wikipedia(request, id):
    """ 需求百科 - 预览 """
    require_wikipedia_obj = models.Require_wikipedia.objects.filter(pk=id).first()
    name = require_wikipedia_obj.name
    content = json.loads(require_wikipedia_obj.content)
    knowledge_card = require_wikipedia_obj.knowledge_card

    knowledge_card_content = models.Knowledge_card.objects.filter(pk=int(knowledge_card)).first()

    card_content = json.loads(knowledge_card_content.content)

    all_card_list = [{'key': key, 'value': value} for key, value in card_content.items()]

    card_dict = {"left": all_card_list[:math.ceil(len(all_card_list) / 2)], "right": all_card_list[math.ceil(len(all_card_list) / 2):]}

    res_data = [{"key": key, "value": value} for key, value in content.items()]

    return render(request, 'require_wikipedia/require_wikipedia_preview.html', {"name": name, "res_data": res_data, 'knowledge_card': knowledge_card, 'card_dict': card_dict})


def edit_require_wikipedia(request, id):
    """ 需求百科 - 编辑 """
    require_wikipedia_obj = models.Require_wikipedia.objects.filter(pk=id).first()
    content_dict = json.loads(require_wikipedia_obj.content)
    content = [{"key": key, "value": value} for key, value in content_dict.items()]
    id = require_wikipedia_obj.id
    name = require_wikipedia_obj.name
    card_id = require_wikipedia_obj.knowledge_card
    all_tem = '，'.join([key for key, value in content_dict.items()])
    return render(request, 'require_wikipedia/edit_require_wikipedia.html', {'id': id, 'all_tem': all_tem, 'name': name, 'content': content, "card_id": card_id})


def delete_require_wikipedia(request, id):
    """ 需求百科 - 删除 """
    models.Require_wikipedia.objects.filter(pk=id).delete()
    return redirect('require_wikipedia')


def search_require_wikipedia(request):
    """ 需求百科 - 搜索 """
    # 查询所有的模板名称
    template_name_list = [{"id": sg_tem.id, "name": sg_tem.name} for sg_tem in models.Wikipedia_template.objects.filter()]

    # 查询所有的需求百科
    search_name = request.GET.get("search_name")
    all_wikipedia_data = models.Require_wikipedia.objects.filter(name__icontains=search_name)
    res_data = [{"id": sg_data.id, "name": sg_data.name, "create_time": sg_data.create_time} for sg_data in all_wikipedia_data]
    return render(request, 'require_wikipedia/require_wikipedia.html', {"template_name_list": template_name_list, "res_data": res_data})

class Knowledge_search(View):
    def get(self,request):
        '''单独百科搜索页面'''
        return render(request,'wikipedia_entry/wikipedia_search.html')

    def post(self,request):
        key_word = request.POST.get('key_word')
        data_obj_lst = models.Require_wikipedia.objects.filter(name__contains=key_word).all()
        new_data = []
        for data_obj in data_obj_lst:
            string = ""
            cont_dic = json.loads(data_obj.content)
            for k,v in cont_dic.items():
                string += k + ":" + v
            # string = string.lstrip(",")
            new_data.append({
                'name':data_obj.name,
                'content': string,
                'id':data_obj.id
            })
        return render(request,'wikipedia_entry/wikipedia_search_page2.html',locals())


def card_template(request):
    """ 知识卡片模板 - 展示 """
    card_obj = models.Card_template.objects.filter()
    return render(request, 'card_template/card_template.html', {'card_obj': card_obj})


class Add_card_template(View):
    """ 知识卡片模板 - 添加 """

    def get(self, request):
        card_template_obj = models.Card_template.objects.filter()
        return render(request, 'card_template/add_card_template.html', {"card_template_obj": card_template_obj})

    def post(self, request):
        name = request.POST.get("name")
        content = request.POST.get("content")
        models.Card_template.objects.create(name=name, content=content)
        return redirect('card_template')


class Edit_card_template(View):
    """ 知识卡片模板 - 编辑 """

    def get(self, request, id):
        card_template_obj = models.Card_template.objects.filter(pk=id).first()
        return render(request, 'card_template/edit_card_template.html', {"card_template_obj": card_template_obj})

    def post(self, request, id):
        name = request.POST.get("name")
        content = request.POST.get("content")
        models.Card_template.objects.filter(pk=id).update(name=name, content=content)
        return redirect('card_template')


def delete_card_template(request, id):
    """ 知识卡片模板 - 删除 """
    models.Card_template.objects.filter(pk=id).delete()
    return redirect('card_template')


def knowledge_card(request):
    """ 知识卡片 - 展示 """
    template_obj = models.Card_template.objects.filter()
    card_obj = models.Knowledge_card.objects.filter()
    res_data = []
    for sg_card in card_obj:
        sg_data_dict = {}
        sg_data_dict["id"] = sg_card.id
        sg_data_dict["name"] = sg_card.name
        sg_data_dict["content"] = '，'.join([sg_data for sg_data in json.loads(sg_card.content).keys()])
        sg_data_dict["create_time"] = sg_card.create_time
        res_data.append(sg_data_dict)

    return render(request, 'knowledge_card/knowledge_card.html', {'template_obj': template_obj, 'card_obj': card_obj, 'res_data': res_data})


class Add_knowledge_card(View):
    """ 知识卡片 - 添加 """

    def get(self, request):
        choiced_card_tempalte_id = request.GET.get("template_choiced")
        choiced_card_tempalte_obj = models.Card_template.objects.filter(id=choiced_card_tempalte_id).first()
        tem_content = choiced_card_tempalte_obj.content
        tem_content_list = tem_content.split('，')
        return render(request, 'knowledge_card/add_knowledge_card.html', {"tem_content_str": tem_content, "tem_content_list": tem_content_list})

    def post(self, request):
        name = request.POST.get("name")
        all_tem = request.POST.get("all_tem")
        con_list = all_tem.split('，')
        con_dict = {}
        for sg_con in con_list:
            con_dict[sg_con] = request.POST.get(sg_con)
        content = json.dumps(con_dict)

        models.Knowledge_card.objects.create(name=name, content=content)
        return redirect('knowledge_card')


class Edit_knowledge_card(View):
    """ 知识卡片 - 编辑 """

    def get(self, request, id):
        Knowledge_card_obj = models.Knowledge_card.objects.filter(pk=id).first()
        name = Knowledge_card_obj.name
        content = json.loads(Knowledge_card_obj.content)
        content_title = '，'.join([sg_con_ti for sg_con_ti in content.keys()])
        content_list = [{'key': key, 'value': value} for key, value in content.items()]
        return render(request, 'knowledge_card/edit_knowledge_card.html', {"id": id, "name": name, "content_title": content_title, "content_list": content_list})

    def post(self, request, id):
        name = request.POST.get("name")
        all_tem = request.POST.get("all_tem")
        con_list = all_tem.split('，')
        con_dict = {}
        for sg_con in con_list:
            con_dict[sg_con] = request.POST.get(sg_con)
        content = json.dumps(con_dict)

        models.Knowledge_card.objects.filter(pk=id).update(name=name, content=content)
        return redirect('knowledge_card')


def delete_knowledge_card(request, id):
    """ 知识卡片 - 删除 """
    models.Knowledge_card.objects.filter(pk=id).delete()
    return redirect('knowledge_card')


def preview_knowledge_card(request, id):
    knowledge_card_obj = models.Knowledge_card.objects.filter(pk=id).first()
    name = knowledge_card_obj.name
    content = json.loads(knowledge_card_obj.content)

    all_card_list = [{'key': key, 'value': value} for key, value in content.items()]

    card_dict = {"left": all_card_list[:math.ceil(len(all_card_list) / 2)], "right": all_card_list[math.ceil(len(all_card_list) / 2):]}

    return render(request, 'knowledge_card/knowledge_card_preview.html', {"name": name, "card_dict": card_dict})


def service_interface(request):
    """ 知识图谱服务接口 """
    return render(request, 'service_interface/service_interface.html')


def noumenon(request):
    """本体页面服务接口"""
    return render(request, 'business_model/table.html')


def noumenon_load(request):
    """本体全部查询接口"""
    try:
        data = requests.post(settings.service_ip + '/ontology/getOntology', )
        res_data = json.loads(data.text)
    except Exception as e:
        res = {'code': 0, 'count': 0, 'msg ': "请求数据库错误", 'data': []}
        return JsonResponse(res)

    count = len(res_data)
    res = {'code': 0, 'count': count, 'data': res_data}
    return JsonResponse(res)


def noumenon_create(request):
    """ 请求创建本体服务窗口接口 """
    if request.method == "GET":
        return render(request, 'business_model/noumenon_add.html')
    else:
        res = {'status': 1}
        return JsonResponse(res)


def noumenon_add(request):
    """ 提交本体创建 """
    noumenon_name = request.GET.get("noumenon_name")
    noumenon_attribute = request.GET.get("noumenon_attribute")
    data = requests.post(settings.service_ip + '/ontology/insertOntology',
                         data={"name": noumenon_name, "attributes": noumenon_attribute})
    res = {'status': 1} if data else {"status": 0}
    return JsonResponse(res)


def noumenon_delete(request):
    """ 本体删除 """
    id = request.GET.get("id")
    data = requests.post(settings.service_ip + '/ontology/deleteOntology', data={"id": id})
    res = {'status': 1} if data else {"status": 0}
    return JsonResponse(res)


def noumenon_edit(request):
    """ 本体更新请求页面 """
    id = request.GET.get("id")
    name = request.GET.get("name")
    attributes = request.GET.get("attributes")
    res = {"id": id, "noumenon_name": name, "noumenon_attribute": attributes}
    return render(request, 'business_model/noumenon_edit.html', context={"noumenon": res})


def noumenon_edit_submit(request):
    """ 本体更新提交 """
    id = request.GET.get("id")
    noumenon_name = request.GET.get("noumenon_name")
    noumenon_attribute = request.GET.get("noumenon_attribute")
    data = requests.post(settings.service_ip + '/ontology/updateOntology',
                         data={"id": id, "name": noumenon_name, "attributes": noumenon_attribute})

    res = {'status': 1} if data else {"status": 0}
    return JsonResponse(res)


def nodes_load(request):
    """实体全部查询接口"""
    pageIndex = request.GET.get('page', 1)
    pageSize = request.GET.get('size', 8)
    entity_node_text = request.GET.get("entity_node_text", "")
    data = requests.post(settings.neo4j_ip + '/kg/node/fuzzy_query')

    return_res = json.loads(data.text)

    res_datas = return_res["data"]["nodes"]
    res_data = []
    for res in res_datas:
        res_dict = {}
        attribute_str = ''
        for i, j in res.items():
            if i == "uuid" or i =="id":
                continue
            elif  i =="name" or i =="label" :
                res_dict["node_"+i] = res[i]
            else:
                attribute_str = str(i) + ":" + str(j) + ";"
        # print(attribute_str)
        if attribute_str.endswith(";"):
            res_dict["node_attribute"] = attribute_str[0:-1]
        else:
            res_dict["node_attribute"] = attribute_str
        res_data.append(res_dict)
    if entity_node_text == "":
        res_data = res_data
    else:
        res_list = []
        for i in res_data:
            if entity_node_text in i.get("node_name"):
                res_list.append(i)
        res_data = res_list
    count = len(res_data)
    pageInator = Paginator(res_data, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []  # 最终返回的结果集合
    for contact in contacts:
        res.append(contact)
    res = {'code': 0, 'count': count, 'data': res}
    return JsonResponse(res)


def node_create(request):
    """提交实体创建"""
    return render(request, "entity/entity_node_add.html")


def node_add(request):
    node_name = request.GET.get("node_name")
    node_label = request.GET.get("node_label")
    node_attribute = request.GET.get("node_attribute")

    print(request.GET)

    node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, node_name))
    data = {"uuid": node_name_uuid, "label": node_label, "name": node_name}

    node_attribute_lists = node_attribute.replace("；", ";").replace("：", ":").split(";")
    try:
        for res in node_attribute_lists:
            if ":" not in res:
                continue
            else:

                data[res.split(":")[0]] = res.split(":")[1]
    except Exception as e:
        res = {"status": 10, "msg": "输入属性格式不正确"}
        return JsonResponse(res)

    data = requests.post(settings.neo4j_ip + '/kg/node/insert', data=data)

    if data:

        History.objects.create(node = node_name,record="新增节点{},节点标签:{},节点属性:{}".format(node_name,node_label,node_attribute_lists))

        res = {'status': 1}
    else:
        res = {"status": 0}

    return JsonResponse(res)


def node_edit(request):
    """本体更新请求页面"""
    if request.method == "GET":
        id = request.GET.get("id")
        # print(id)
        node_name = request.GET.get("node_name")
        node_label = request.GET.get("node_label")
        node_attribute = request.GET.get("node_attribute")
        res = {"id": id, "node_name": node_name, "node_label": node_label, "node_attribute": node_attribute}
        return render(request, 'entity/entity_node_edit.html', context={"node": res})
    else:
        return HttpResponse('123456')


def node_edit_submit(request):
    """本体更新提交"""
    id = request.GET.get("id")
    node_name = request.GET.get("node_name")
    node_label = request.GET.get("node_label")
    node_attribute = request.GET.get("node_attribute")

    node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, node_name))
    data = {"uuid": node_name_uuid, "label": node_label, "name": node_name}

    node_attribute_lists = node_attribute.replace("；", ";").replace("：", ":").split(";")
    try:
        for res in node_attribute_lists:
            if ":" not in res:
                continue
            else:

                data[res.split(":")[0]] = res.split(":")[1]
    except Exception as e:
        res = {"status": 10, "msg": "输入属性格式不正确"}
        return JsonResponse(res)

    data = requests.post(settings.neo4j_ip + '/kg/node/update', data=data)
    data = data.json()

    if data['code'] == 1:
        History.objects.create(node=node_name,
                               record="修改节点{},节点标签:{},节点属性:{}".format(node_name, node_label, node_attribute_lists))
        res = {"status": 1}
    elif data["code"] == 2:
        res = {"status": 2, "msg": "修改节点不存在"}
    else:
        res = {"status": 0}
    return JsonResponse(res)


def node_delete(request):
    """本体删除"""
    name = request.GET.get("name")

    node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, name))
    # print(node_name_uuid)



    data = requests.post(settings.neo4j_ip + '/kg/node/delete',
                         data={"uuid": node_name_uuid}).json()

    # print(data)
    if data['code'] == 1:
        res = {"status": 1,'msg':data['msg']}
        # History.objects.create(node=name,
        #                        record="删除节点{}".format(name))
    else:
        res = {"status": data['code'],'msg':data['msg']}

    return JsonResponse(res)


def edge_load(request):
    """ 关系展示 """
    pageIndex = request.GET.get('page', 1)
    pageSize = request.GET.get('size', 8)
    edge_text = request.GET.get("edge_text", "")
    data = requests.post(settings.neo4j_ip + '/kg/relation/query', )
    return_res = json.loads(data.text)
    res_datas = return_res["data"]["edges"]
    res_data = []
    for res in res_datas:
        res_dict={}
        res_dict["edge_type"] = res["type"]
        res_dict["start_node"] = res["start_node_name"]
        res_dict["end_node"] = res["end_node_name"]
        attribute_str = ''
        for i,j in res["properties"].items():
            attribute_str = str(i) +":"+str(j) +";"
        if attribute_str.endswith(";"):
            res_dict["attribute"] = attribute_str[0:-1]
        else:
            res_dict["attribute"] = attribute_str
        res_data.append(res_dict)
    if edge_text == "":
        res_data = res_data
    else:
        res_list = []
        for i in res_data:
            if edge_text in i.get("edge_type"):
                res_list.append(i)
        res_data = res_list

    pageInator = Paginator(res_data, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []  # 最终返回的结果集合
    for contact in contacts:
        res.append(contact)
    count = len(res_data)
    res = {'code': 0, 'count': count, 'data': res}
    return JsonResponse(res)


def edge_create(request):
    """请求实体关系创建页面"""
    return render(request, "entity/entity_edge_add.html")


def edge_add(request):
    """ 提交实体关系增加信息 """
    edge_type = request.GET.get("edge_type")
    start_node = request.GET.get("start_node")
    end_node = request.GET.get("end_node")
    attribute = request.GET.get("attribute")

    start_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, start_node))
    end_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, end_node))
    data = {"relation_type": edge_type, "start_node_uuid": start_node_uuid, "end_node_uuid": end_node_uuid}

    node_attribute_lists = attribute.replace("；", ";").replace("：", ":").split(";")
    try:
        for res in node_attribute_lists:
            if ":" not in res:
                continue
            else:

                data[res.split(":")[0]] = res.split(":")[1]
    except Exception as e:
        res = {"status": 10, "msg": "输入属性格式不正确"}
        return JsonResponse(res)

    data = requests.post(settings.neo4j_ip + '/kg/edge/insert', data=data)

    if data:
        History.objects.create(node=edge_type,
                               record="新增关系{},起始节点:{},终止节点:{},关系属性:{}".format(edge_type, start_node, end_node,
                                                                              node_attribute_lists))

        res = {'status': 1}
    else:
        res = {"status": 0}

    return JsonResponse(res)


def edge_edit(request):
    """本体关系更新请求页面"""
    id = request.GET.get("id")
    edge_type = request.GET.get("edge_type")
    start_node = request.GET.get("start_node")
    end_node = request.GET.get("end_node")
    attribute = request.GET.get("attribute")
    res = {"id": id, "edge_type": edge_type, "start_node": start_node, "end_node": end_node, "attribute": attribute}
    return render(request, 'entity/entity_edge_edit.html', context={"edge": res})


def edge_edit_submit(request):
    """本体关系更新提交"""
    id = request.GET.get("id")
    edge_type = request.GET.get("edge_type")
    start_node = request.GET.get("start_node")
    end_node = request.GET.get("end_node")
    attribute = request.GET.get("attribute")

    start_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, start_node))
    end_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, end_node))
    data = {"relation_type": edge_type, "start_node_uuid": start_node_uuid, "end_node_uuid": end_node_uuid}

    node_attribute_lists = attribute.replace("；", ";").replace("：", ":").split(";")
    try:
        for res in node_attribute_lists:
            if ":" not in res:
                continue
            else:

                data[res.split(":")[0]] = res.split(":")[1]
    except Exception as e:
        res = {"status": 10, "msg": "输入属性格式不正确"}
        return JsonResponse(res)

    data = requests.post(settings.neo4j_ip + '/kg/edge/update', data=data)
    data = data.json()

    if data['code'] == 1:
        History.objects.create(node=edge_type,
                               record="修改关系{},起始节点:{},终止节点:{},关系属性:{}".format(edge_type, start_node, end_node,
                                                                              node_attribute_lists))

        res = {"status": 1}
    elif data["code"] == 2:
        res = {"status": 2, "msg": "修改节点不存在"}
    else:
        res = {"status": 0}
    return JsonResponse(res)


def edge_delete(request):
    """本体关系删除"""
    edge_type = request.GET.get("edge_type")
    start_node = request.GET.get("start_node")
    end_node = request.GET.get("end_node")

    start_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, start_node))
    end_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, end_node))

    data = requests.post(settings.neo4j_ip + '/kg/edge/delete',
                         data={"relation_type": edge_type, "start_node_uuid": start_node_uuid,
                               "end_node_uuid": end_node_uuid})
    if data:
        res = {"status": 1}
        History.objects.create(node=edge_type,
                               record="删除关系{},起始节点:{},终止节点:{}".format(edge_type, start_node, end_node))

    else:
        res = {"status": 0}

    return JsonResponse(res)


def node_analysis(request):
    if request.method == "GET":
        return render(request, "spectrum_analysis/node_analysis.html")
    elif request.method == "POST":
        node_name = request.POST.get("node_name")
        # node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, node_name))

        headers = {'content_type': 'multipart/form-data; boundary=--------------------------879346903113862253548472'}

        data = requests.post(settings.neo4j_ip + '/kg/node/fuzzy_query',
                             data={"name": node_name})
        data = data.json()

        datas = []
        for sg_data in data.get('data').get('nodes'):
            datas.append({"id": sg_data.get("id"), "uuid": sg_data.get("uuid"), "label": sg_data.get("label"), "properties": {"name": sg_data.get("name"), "create_time": sg_data.get("created_time")}})

        edgeall = []
        for sg_data in data.get('data').get('edges'):
            edgeall.append({
                "source": str(sg_data.get("start_node_id")),
                "target": str(sg_data.get("end_node_id")),
                "type": sg_data.get("type"),
                "id": sg_data.get("id")
            })

        res_data = {'code': 1, "msg": "success", 'data': {"nodes": datas, "edges": edgeall}}

        return JsonResponse(res_data)
    else:
        return render(request, 'not_find.html')


def association_analysis(request):
    """ 关联图谱展示 """
    if request.method == "GET":
        sign = request.GET.get("sign")
        if sign == "0":
            return render(request, 'spectrum_analysis/datashow.html', {"sign": sign})
        else:
            return render(request, 'service_interface/map_analysis.html', {"sign": sign})
    elif request.method == "POST":
        start_point = request.POST.get("start_point")
        start_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, start_point))

        end_point = request.POST.get("end_point")
        end_node_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, end_point))

        maxnum = request.POST.get("max_num", "")

        headers = {'content_type': 'multipart/form-data; boundary=--------------------------879346903113862253548472'}

        data = requests.post(settings.neo4j_ip + '/kg/path/query',
                             data={"start_node_uuid": start_node_uuid, "end_node_uuid": end_node_uuid, "headers": headers, "level": maxnum})

        data = data.json()

        datas = []
        for sg_data in data.get('data').get('nodes'):
            datas.append({"id": sg_data.get("id"), "uuid": sg_data.get("uuid"), "label": sg_data.get("label"), "properties": {"name": sg_data.get("name"), "create_time": sg_data.get("created_time")}})

        edgeall = []
        for sg_data in data.get('data').get('edges'):
            edgeall.append({
                "source": str(sg_data.get("start_node_id")),
                "target": str(sg_data.get("end_node_id")),
                "type": sg_data.get("type"),
                "id": sg_data.get("id")
            })

        res_data = {'code': 1, "msg": "success", 'data': {"nodes": datas, "edges": edgeall}}
        return JsonResponse(res_data)
    else:
        return render(request, 'not_find.html')


def node_side_nodes(request):
    """ 双击图谱node时，返回该点周边的点与该点的关系 """
    id = request.POST.get("id")
    uuid = request.POST.get("uuid")
    label = request.POST.get("label")
    level = 1
    headers = {'content_type': 'multipart/form-data; boundary=--------------------------879346903113862253548472'}

    data = requests.post(settings.neo4j_ip + '/kg/graph/query',
                         data={"start_node_uuid": uuid, "level": level})

    data = data.json()

    datas = []
    for sg_data in data.get('data').get('nodes'):
        datas.append({"id": sg_data.get("id"), "uuid": sg_data.get("uuid"), "label": sg_data.get("label"),
                      "properties": {"name": sg_data.get("name"), "create_time": sg_data.get("created_time")}})

    edgeall = []
    for sg_data in data.get('data').get('edges'):
        edgeall.append({
            "source": str(sg_data.get("start_node_id")),
            "target": str(sg_data.get("end_node_id")),
            "type": sg_data.get("type"),
            "id": sg_data.get("id")
        })

    res = {'code': 1, "msg": "success", 'data': {"nodes": datas, "edges": edgeall}}
    return JsonResponse(res)


def map_analysis(request):
    """ 地图展示 """
    if request.method == "GET":
        return render(request, 'spectrum_analysis/mapshow.html')
    elif request.method == "POST":
        entity = request.POST.get("entity")
        entity_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, entity))
        # headers = {'content_type': 'multipart/form-data; boundary=--------------------------879346903113862253548472'}

        try:
            res_data = requests.post(settings.neo4j_ip + '/kg/node/query',
                                     data={"uuid": entity_uuid})
            res_data = res_data.json()
            # print(res_data)

            geoCoordMap = {}
            data = []
            for sg_data in res_data.get('data').get('nodes'):
                geoCoordMap[sg_data.get("name")] = eval(sg_data.get("area"))
                data.append(sg_data)
            res = {'code': 1, "msg": "success", 'data': {"geoCoordMap": geoCoordMap, "data": data}}
        except Exception:
            res = {'code': 1, "msg": "no_found", 'data': {"geoCoordMap": [], "data": []}}
        return JsonResponse(res)
    else:
        return render(request, 'not_find.html')


def analysis_aide(request):
    """ 分析助手请求页面接口 """
    return render(request, 'spectrum_analysis/analysis_aide.html')


def histogram(request):
    """直方图分析接口"""

    histogram_text = request.POST.get("histogram_text")
    projects = models.Project.objects.filter().all()
    girth = []
    if projects:
        for res_data in projects:
            girth.append(res_data.money)

    girth = [109, 128, 107, 111, 49, 65, 102, 50, 115, 129, 120, 51, 72, 90, 45, 75, 131, 106, 67, 48, 97, 125, 64, 92,
             48, 47, 85, 116, 64, 62, 98, 66, 125, 77, 81, 68, 68, 102, 69, 76, 73, 90, 52, 81, 104, 108, 118, 121, 117,
             126, 57, 128, 92, 84, 47, 95, 45, 100, 45, 63, 59, 110, 102, 95, 112, 119, 68, 107, 104, 55, 115, 128, 69,
             97, 81, 46, 69, 92, 105, 77, 92, 129, 109, 117, 104, 72, 107, 52, 54, 95, 121, 89, 106, 125, 121, 127, 131,
             90, 129, 67, 94, 123, 49, 79, 69, 89, 82, 75, 62, 82, 129, 88, 134, 133, 129, 89, 99, 90, 97, 74, 65, 56,
             73, 74, 124, 68, 89, 62, 111, 65, 84, 80, 122, 48, 133, 72, 98, 124, 130, 82, 89, 75, 102, 119, 89, 105,
             56, 130, 88, 69, 50, 107, 91, 79, 120, 60, 92, 47, 60, 88, 107, 62, 93, 91, 52, 81, 75, 105, 75, 63, 49,
             69]
    res = {"code": 1, "msg": "success", "data": girth}
    return JsonResponse(res)


def bar_chart(request):
    """ 柱状图分析接口 """
    # TODO 分析直方图需要节点统计
    if request.method == "POST":
        histogram_text = request.POST.get("histogram_text")
        xAxis_data = []
        value_data = []

        # project = models.Project.objects.filter(project_name__contains=histogram_text).first()
        # if project:
        #     res_datas = models.Histogram.objects.filter(project_id=str(project.id))
        #     for res_data in res_datas:
        #         xAxis_data.append(res_data.class_name)
        #         value_data.append(int(res_data.require_count))
        his_obj = models.New_histogram.objects.filter(search_word__contains=histogram_text).first()
        if his_obj:
            hid = his_obj.id
            details = models.His_details.objects.filter(new_histogram__id=hid).order_by("happen_time").all()
            data = {}
            for det in details:
                date_time = det.happen_time.strftime("%Y-%m")
                if date_time in data:
                    data[date_time] += 1
                else:
                    data[date_time] = 1
            for k,v in data.items():
                xAxis_data.append(k)
                value_data.append(v)
            res = {"code": 1, "msg": "success", "data": {"xAxis_data": xAxis_data, "value_data": value_data}}
        else:
            res = {"code": 1, "msg": "未查询到相关信息", "data": {"xAxis_data": xAxis_data, "value_data": value_data}}
        return JsonResponse(res)


def timeline(request):
    """时间线"""
    # TODO 时间线需要节点的发展历程
    timeline_text = request.GET.get("Timeline_text")
    data = []
    project = models.Project.objects.filter(project_name=timeline_text).first()
    if project:
        res_datas = models.Timeline.objects.filter(project_id=str(project.id)).order_by("time")
        for res_data in res_datas:
            res_dict = {}
            res_dict["label"] = res_data.event_name
            res_dict["date"] = res_data.time
            data.append(res_dict)
        res = {"code": 1, "msg": "success", "data": data}
    else:
        res = {"code": 1, "msg": "未查询到相关信息", "data": data}
    return JsonResponse(res)


def history_load(request):
    """历史分析接口"""
    # TODO 历史需要历史操作记录
    history_text = request.GET.get("history_text")
    # res_data = History.objects.filter(node__contains=history_text)
    # data = []
    # for res in res_data:
    #     res_dict = {}
    #     res_dict["id"] = res.id
    #     res_dict["node"] = res.node
    #     res_dict["record"] = res.record
    #     res_dict["time"] = res.time
    #     data.append(res_dict)
    # data1 = [{"node": "项目", "record": "新增", "time": '2020-02-23'},
    #          {"node": "项目", "record": "需求更改", "time": '2020-03-23'},
    #          {"node": "项目", "record": "项目结束", "time": '2020-05-23'}, ]
    # count = len(data)
    data = []
    his_obj = models.New_histogram.objects.filter(search_word__contains=history_text).first()
    if his_obj:
        hid = his_obj.id
        hname = his_obj.search_word
        details = models.His_details.objects.filter(new_histogram__id=hid).order_by("happen_time").all()
        for res in details:
            res_dict = {}
            res_dict["id"] = res.id
            res_dict["node"] = hname
            res_dict["record"] = res.details
            res_dict["time"] = res.happen_time
            data.append(res_dict)
    count = len(data)
    res = {"code": 0, "count": count, "msg": "success", "data": data}
    return JsonResponse(res)


def history_delete(request):
    """历史数据删除接口"""
    id = request.GET.get("id")
    data = History.objects.filter(id=id).delete()
    res = {"status": 1} if data else {"status": 0}
    return JsonResponse(res)


def data_mining_model(request):
    sign = request.GET.get("sign")
    delete_sign = request.GET.get("delete_sign")
    import_sign = request.GET.get("import_sign")

    # 查看数据挖掘模型表
    data_mining_obj = models.Data_mining.objects.filter()
    # 查看知识推理模型表
    knowledge_reasoning_obj = models.Knowledge_reasoning.objects.filter()
    # 查看关联分析模型表
    correlation_analysis_obj = models.Correlation_analysis.objects.filter()

    return render(request, 'data_mining_model/business_model_building.html',
                  {"data_mining_obj": data_mining_obj, "knowledge_reasoning_obj": knowledge_reasoning_obj, "correlation_analysis_obj": correlation_analysis_obj, "sign": sign,
                   "delete_sign": delete_sign, "import_sign": import_sign})


class Model_import(View):
    """ 模型导入 """

    def get(self, request):
        # 模型文件导入
        base_model_obj = models.Base_model.objects.filter(type="数据挖掘模型")
        return render(request, 'data_mining_model/model_import.html', {"base_model_obj": base_model_obj})

    def post(self, request):
        uuid = request.POST.get("uuid", "")
        name = request.POST.get("name", "")
        label = request.POST.get("label", "")
        configuration = request.POST.get("configuration", "")
        try:
            models.Data_mining.objects.create(name=name, label=label, uuid=uuid, configuration=configuration)
            res_data = {"code": 1, "msg": "模型导入成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型导入失败！！！"}
        return JsonResponse(res_data)


class Knowledge_reasoning_model_import(View):
    """ 知识推理模型导入 """

    def get(self, request):
        base_model_obj = models.Base_model.objects.filter(type="知识推理模型")
        return render(request, 'knowledge_reasoning_model/model_import.html', {"base_model_obj": base_model_obj})

    def post(self, request):
        name = request.POST.get("name", "")
        start_node_uuid = request.POST.get("start_node_uuid", "")
        relation_type = request.POST.get("relation_type", "")
        configuration = request.POST.get("configuration", "")
        try:
            models.Knowledge_reasoning.objects.create(name=name, start_node_uuid=start_node_uuid, relation_type=relation_type, configuration=configuration)
            res_data = {"code": 1, "msg": "模型导入成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型导入失败！！！"}
        return JsonResponse(res_data)


class Correlation_analysis_model_import(View):
    """ 关联分析模型导入 """

    def get(self, request):
        base_model_obj = models.Base_model.objects.filter(type="关联分析模型")
        return render(request, 'correlation_analysis_model/model_import.html', {"base_model_obj": base_model_obj})

    def post(self, request):
        name = request.POST.get("name", "")
        start_node_uuid = request.POST.get("start_node_uuid", "")
        end_node_uuid = request.POST.get("end_node_uuid", "")
        configuration = request.POST.get("configuration", "")
        try:
            models.Correlation_analysis.objects.create(name=name, start_node_uuid=start_node_uuid, end_node_uuid=end_node_uuid, configuration=configuration)
            res_data = {"code": 1, "msg": "模型导入成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型导入失败！！！"}
        return JsonResponse(res_data)


class Model_edit(View):
    """ 数据挖掘模型修改 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Data_mining.objects.filter(pk=model_id).first()
        return render(request, 'data_mining_model/model_edit.html', {"model_obj": model_obj})

    def post(self, request):
        id = request.POST.get("id", "")
        uuid = request.POST.get("uuid", "")
        name = request.POST.get("name", "")
        label = request.POST.get("label", "")
        try:
            models.Data_mining.objects.filter(pk=id).update(name=name, label=label, uuid=uuid)
            res_data = {"code": 1, "msg": "模型参数调整成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型参数调整失败！！！"}
        return JsonResponse(res_data)

class Model_configuration_edit(View):
    """ 数据挖掘模型配置更改 """
    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Data_mining.objects.filter(pk=model_id).first()
        return render(request, 'data_mining_model/model_configuration_edit.html', {"model_obj": model_obj})

    def post(self, request):
        id = request.POST.get("id", "")
        name = request.POST.get("name", "")
        configuration = request.POST.get("configuration", "")
        try:
            models.Data_mining.objects.filter(pk=id).update(name=name, configuration=configuration)
            res_data = {"code": 1, "msg": "模型配置修改成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型配置修改失败！！！"}
        return JsonResponse(res_data)

def model_status_edit(request):
    """ 数据挖掘模型状态更改 """
    id = request.POST.get("model_id")
    sign = request.POST.get("sign")
    try:
        if sign == "1":
            models.Data_mining.objects.filter(pk=id).update(status="运行中")
            res = {"code": "1", "msg": "运行中"}
        else:
            models.Data_mining.objects.filter(pk=id).update(status="未运行")
            res = {"code": "1", "msg": "未运行"}
    except Exception:
        res = {"code": "0", "msg": "模型 运行/终止 异常!!!"}
    return JsonResponse(res)


def knowledge_reasoning_model_status_edit(request):
    """ 知识推理模型状态修改 """
    id = request.POST.get("model_id")
    sign = request.POST.get("sign")
    try:
        if sign == "1":
            models.Knowledge_reasoning.objects.filter(pk=id).update(status="运行中")
            res = {"code": "1", "msg": "运行中"}
        else:
            models.Knowledge_reasoning.objects.filter(pk=id).update(status="未运行")
            res = {"code": "1", "msg": "未运行"}
    except Exception:
        res = {"code": "0", "msg": "模型 运行/终止 异常!!!"}
    return JsonResponse(res)


def correlation_analysis_model_status_edit(request):
    """ 关联分析模型状态修改 """
    id = request.POST.get("model_id")
    sign = request.POST.get("sign")
    try:
        if sign == "1":
            models.Correlation_analysis.objects.filter(pk=id).update(status="运行中")
            res = {"code": "1", "msg": "运行中"}
        else:
            models.Correlation_analysis.objects.filter(pk=id).update(status="未运行")
            res = {"code": "1", "msg": "未运行"}
    except Exception:
        res = {"code": "0", "msg": "模型 运行/终止 异常!!!"}
    return JsonResponse(res)


def model_delete(request):
    """ 数据挖掘模型删除 """
    id = request.GET.get("model_id")
    try:
        models.Data_mining.objects.filter(pk=id).delete()
        res = {"code": "1", "msg": "数据挖掘模型删除成功"}
    except Exception:
        res = {"code": "0", "msg": "数据挖掘模型删除失败，请重试！！！"}
    return JsonResponse(res)


def knowledge_reasoning_model_delete(request):
    """ 知识推理模型删除 """
    id = request.GET.get("model_id")
    try:
        models.Knowledge_reasoning.objects.filter(pk=id).delete()
        res = {"code": "1", "msg": "知识推理模型删除成功"}
    except Exception:
        res = {"code": "0", "msg": "知识推理模型删除失败，请重试！！！"}
    return JsonResponse(res)


def correlation_analysis_model_delete(request):
    """ 关联分析模型删除 """
    id = request.GET.get("model_id")
    try:
        models.Correlation_analysis.objects.filter(pk=id).delete()
        res = {"code": "1", "msg": "关联分析模型删除成功"}
    except Exception:
        res = {"code": "0", "msg": "关联分析模型删除失败，请重试！！！"}
    return JsonResponse(res)


class Knowledge_reasoning_model_edit(View):
    """ 知识推理模型修改 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Knowledge_reasoning.objects.filter(pk=model_id).first()
        return render(request, 'knowledge_reasoning_model/model_edit.html', {"model_obj": model_obj})

    def post(self, request):
        id = request.POST.get("id", "")
        name = request.POST.get("name", "")
        start_node_uuid = request.POST.get("start_node_uuid", "")
        relation_type = request.POST.get("relation_type", "")

        try:
            models.Knowledge_reasoning.objects.filter(pk=id).update(name=name, start_node_uuid=start_node_uuid, relation_type=relation_type)
            res_data = {"code": 1, "msg": "模型参数调整成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型参数调整失败！！！"}
        return JsonResponse(res_data)

class Knowledge_reasoning_model_configuration_edit(View):
    """ 知识推理模型配置修改 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Knowledge_reasoning.objects.filter(pk=model_id).first()
        return render(request, 'knowledge_reasoning_model/model_configuration_edit.html', {"model_obj": model_obj})

    def post(self, request):
        id = request.POST.get("id", "")
        name = request.POST.get("name", "")
        configuration = request.POST.get("configuration", "")

        try:
            models.Knowledge_reasoning.objects.filter(pk=id).update(name=name, configuration=configuration)
            res_data = {"code": 1, "msg": "模型配置修改成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型配置修改失败！！！"}
        return JsonResponse(res_data)


class Correlation_analysis_model_edit(View):
    """ 关联分析模型修改 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Correlation_analysis.objects.filter(pk=model_id).first()
        return render(request, 'correlation_analysis_model/model_edit.html', {"model_obj": model_obj})

    def post(self, request):
        id = request.POST.get("id", "")
        name = request.POST.get("name", "")
        start_node_uuid = request.POST.get("start_node_uuid", "")
        end_node_uuid = request.POST.get("end_node_uuid", "")
        try:
            models.Correlation_analysis.objects.filter(pk=id).update(name=name, start_node_uuid=start_node_uuid, end_node_uuid=end_node_uuid)
            res_data = {"code": 1, "msg": "模型参数调整成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型参数调整失败！！！"}
        return JsonResponse(res_data)


class Correlation_analysis_model_configuration_edit(View):
    """ 关联分析模型配置更改 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        model_obj = models.Correlation_analysis.objects.filter(pk=model_id).first()
        return render(request, 'correlation_analysis_model/model_configuration_edit.html', {"model_obj": model_obj})

    def post(self, request):
        id = request.POST.get("id", "")
        name = request.POST.get("name", "")
        configuration = request.POST.get("configuration", "")
        try:
            models.Correlation_analysis.objects.filter(pk=id).update(name=name, configuration=configuration)
            res_data = {"code": 1, "msg": "模型配置修改成功"}
        except Exception:
            res_data = {"code": 0, "msg": "模型配置修改失败！！！"}
        return JsonResponse(res_data)


class Model_run(View):
    """ 数据挖掘运行 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        return render(request, 'data_mining_model/model_map_show.html', {"model_id": model_id})

    def post(self, request):
        id = request.POST.get("model_id")
        data_mining_obj = models.Data_mining.objects.filter(pk=id).first()
        uuid = data_mining_obj.uuid

        data = requests.post(settings.neo4j_ip + '/kg/node/query',
                             data={"uuid ": uuid})
        data = data.json()

        datas = []
        for sg_data in data.get('data').get('nodes'):
            datas.append({"id": sg_data.get("id"), "uuid": sg_data.get("uuid"), "label": sg_data.get("label"), "properties": {"name": sg_data.get("name"), "create_time": sg_data.get("created_time")}})

        edgeall = []
        for sg_data in data.get('data').get('edges'):
            edgeall.append({
                "source": str(sg_data.get("start_node_id")),
                "target": str(sg_data.get("end_node_id")),
                "type": sg_data.get("type"),
                "id": sg_data.get("id")
            })

        res_data = {'code': 1, "msg": "success", 'data': {"nodes": datas, "edges": edgeall}}

        return JsonResponse(res_data)


class Knowledge_reasoning_model_run(View):
    """ 知识推理模型运行 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        return render(request, 'knowledge_reasoning_model/model_map_show.html', {"model_id": model_id})

    def post(self, request):
        id = request.POST.get("model_id")
        knowledge_reasoning_obj = models.Knowledge_reasoning.objects.filter(pk=id).first()
        start_node_uuid = knowledge_reasoning_obj.start_node_uuid
        relation_type = json.dumps([knowledge_reasoning_obj.relation_type])

        headers = {'content_type': 'multipart/form-data; boundary=--------------------------879346903113862253548472'}
        data = requests.post(settings.neo4j_ip + '/kg/graph/query',
                             data={"start_node_uuid": start_node_uuid, "relation_type": relation_type, "headers": headers})
        data = data.json()

        datas = []
        for sg_data in data.get('data').get('nodes'):
            datas.append({"id": sg_data.get("id"), "uuid": sg_data.get("uuid"), "label": sg_data.get("label"), "properties": {"name": sg_data.get("name"), "create_time": sg_data.get("created_time")}})

        edgeall = []
        for sg_data in data.get('data').get('edges'):
            edgeall.append({
                "source": str(sg_data.get("start_node_id")),
                "target": str(sg_data.get("end_node_id")),
                "type": sg_data.get("type"),
                "id": sg_data.get("id")
            })

        res_data = {'code': 1, "msg": "success", 'data': {"nodes": datas, "edges": edgeall}}

        return JsonResponse(res_data)


class Correlation_analysis_model_run(View):
    """ 关联分析模型运行 """

    def get(self, request):
        model_id = request.GET.get("model_id")
        return render(request, 'correlation_analysis_model/model_map_show.html', {"model_id": model_id})

    def post(self, request):
        id = request.POST.get("model_id")
        correlation_analysis_obj = models.Correlation_analysis.objects.filter(pk=id).first()
        start_node_uuid = correlation_analysis_obj.start_node_uuid
        end_node_uuid = correlation_analysis_obj.end_node_uuid

        headers = {'content_type': 'multipart/form-data; boundary=--------------------------879346903113862253548472'}
        data = requests.post(settings.neo4j_ip + '/kg/path/query',
                             data={"start_node_uuid": start_node_uuid, "end_node_uuid": end_node_uuid, "headers": headers})
        data = data.json()

        datas = []
        for sg_data in data.get('data').get('nodes'):
            datas.append({"id": sg_data.get("id"), "uuid": sg_data.get("uuid"), "label": sg_data.get("label"), "properties": {"name": sg_data.get("name"), "create_time": sg_data.get("created_time")}})

        edgeall = []
        for sg_data in data.get('data').get('edges'):
            edgeall.append({
                "source": str(sg_data.get("start_node_id")),
                "target": str(sg_data.get("end_node_id")),
                "type": sg_data.get("type"),
                "id": sg_data.get("id")
            })

        res_data = {'code': 1, "msg": "success", 'data': {"nodes": datas, "edges": edgeall}}

        return JsonResponse(res_data)


def bar(request):
    return render(request, "entity/entity_page.html")


def api_manager(request):
    return render(request,"api_manager/api_manager.html")


def api_load(request):
    pageIndex = request.GET.get('page', 1)
    pageSize = request.GET.get('size', 8)
    objs = models.Api_manage.objects.all()
    res_data = []
    for obj in objs:
        res_data.append({
            "api_id":obj.id,
            "api_name":obj.name,
            "api_type":obj.type.name,
            "api_type_id":obj.type.id,
            "api_url":obj.type.url,
            "created_time":obj.created_time.strftime("%Y-%m-%d %X")
        })
    pageInator = Paginator(res_data, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []  # 最终返回的结果集合
    for contact in contacts:
        res.append(contact)
    count = len(res_data)
    res = {'code': 0, 'count': count, 'data': res}
    return JsonResponse(res)


def api_create(request):
    api_objs = models.Api.objects.all()
    return render(request, "api_manager/api_create.html",{"api_objs":api_objs})


def api_add(request):
    api_name = request.POST.get("api_name")
    api_type_id = int(request.POST.get("api_type"))
    api_obj = models.Api.objects.filter(pk=api_type_id).first()
    api_manager_obj = models.Api_manage.objects.filter(name=api_name).first()
    # print(api_manager_obj)
    if not api_manager_obj:
        models.Api_manage.objects.create(name=api_name,type=api_obj)
        data = {
            'status':1,
            'msg':"创建成功"
        }
    else:
        data = {
            'status':2,
            'msg':"接口名已存在"
        }

    return JsonResponse(data)


def api_edit(request):
    if request.method == "GET":
        api_name = request.GET.get("api_name")
        api_type = request.GET.get("api_type")
        api_id = request.GET.get("id")
        res = {"api_name": api_name, "api_type": api_type,"api_id":api_id}
        return render(request,"api_manager/api_edit.html", locals())
    else:
        api_name = request.POST.get("api_name")
        api_id = request.POST.get("api_id")
        obj = models.Api_manage.objects.filter(pk=int(api_id)).first()
        obj.name = api_name
        obj.save()
        return JsonResponse({'status':1})


def api_del(request):
    api_name = request.GET.get('name')
    try:
        models.Api_manage.objects.filter(name=api_name).delete()
        return JsonResponse({"status":1})
    except Exception as e:
        return JsonResponse({'status':2})



def api_run(request):

    re_url = request.POST.get("api_url")

    return redirect(re_url)


def up_node_file(request):
    file_obj = request.FILES.get('file')
    file_path = os.path.join(project_base_path, 'upload_file', file_obj.name)
    try:
        with open(file_path, 'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk, )
    except Exception as e:
        pass

    res_data = insert_csv(file_path)
    data_l = []
    for i in res_data:
        node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, i['node_name']))
        label = i['node_label']
        data = {"uuid":node_name_uuid,"label":label,"name":i['node_name']}
        node_attribute_lists = i['node_attribute'].replace("；", ";").replace("：", ":").split(";")
        try:
            for res in node_attribute_lists:
                if ":" not in res:
                    continue
                else:

                    data[res.split(":")[0]] = res.split(":")[1]
        except Exception as e:
            res = {"status": 10, "msg": "输入属性格式不正确"}
            return JsonResponse(res)

        data_l.append(data)
    data = json.dumps({'data':data_l})
    res = requests.post(settings.neo4j_ip + 'kg/node/batch/insert', data=data).json()
    if res:
        return JsonResponse({'status':1,'msg':'插入成功'})
    else:
        return JsonResponse({'status':2,'msg':'插入失败'})


def up_edge_file(request):
    file_obj = request.FILES.get('file')
    file_path = os.path.join(project_base_path, 'upload_file', file_obj.name)
    try:
        with open(file_path, 'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk, )
    except Exception as e:
        pass

    res_data = insert_csv(file_path)
    data_l = []
    for i in res_data:
        st_node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, i['start_node']))
        en_node_name_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, i['end_node']))
        data = {"relation_type": i['edge_type'], "start_node_uuid": st_node_name_uuid, "end_node_uuid": en_node_name_uuid}
        edge_attribute_lists = i['edge_attribute'].replace("；", ";").replace("：", ":").split(";")
        try:
            for res in edge_attribute_lists:
                if ":" not in res:
                    continue
                else:

                    data[res.split(":")[0]] = res.split(":")[1]
        except Exception as e:
            res = {"status": 10, "msg": "输入属性格式不正确"}
            return JsonResponse(res)

        data_l.append(data)
    data = json.dumps({'data':data_l})
    # print(data)
    res = requests.post(settings.neo4j_ip + 'kg/edge/batch/insert', data=data).json()
    if res:
        # print(res)
        return JsonResponse({'status':1,'msg':'插入成功'})
    else:
        return JsonResponse({'status':2,'msg':'插入失败'})
